<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\VerifyCode;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller {
    public function index() {
        return response()->json( [ 'success'=>1 ], 201 );
    }

    // 查看验证码
    public function showVers()
    {
        $vercode = VerifyCode::orderBy('id', 'desc')->get();;
        return response()->json( ["isok"=>"1",
        'data'=>[
            'vercode' => $vercode,
            ]
        ], 201 );
    }

    // 检查登录
    public function checkLogin(Request $request){
        return response()->json( [
            "isok"=>"0",
            'errors' => $validator->errors()
        ], 422 );
    }
    public function sendVerificationCode( Request $request ) {
        // 验证手机号格式
        $validator = Validator::make( $request->all(), [
            'phone' => 'required|regex:/^1[3-9]\d{9}$/'
        ] );

        if ( $validator->fails() ) {
            return response()->json( [
                "isok"=>"0",
                'errors' => $validator->errors()
            ], 422 );
        }

        // 删除旧验证码（如果存在）
        VerifyCode::where( 'phone', $request->phone )->delete();

        // 生成验证码（4位数字）
        $code = str_pad( mt_rand( 0, 9999 ), 4, '0', STR_PAD_LEFT );

        // 创建新验证码记录
        $verifyCode = VerifyCode::create( [
            'phone' => $request->phone,
            'code' => $code,
            'expired_at' => Carbon::now()->addMinutes( 5 )
        ] );

        // 这里可以添加发送短信的逻辑（示例使用固定验证码）
        // sendSMS( $request->phone, "您的验证码是：{$code}，5分钟内有效" );

        return response()->json( ["isok"=>"1",
            'data'=>[
                'message' => '验证码已发送',
                'code'=>$code,
                'expired_at' => $verifyCode->expired_at->format( 'Y-m-d H:i:s' )
                ]
            ], 201 );
    }

    // 注册接口

    public function signup( Request $request ) {
        $request->validate( [
            'account' => 'required|regex:/^1[3-9]\d{9}$/',
            'code' => 'required|string',
            'password' => 'required|string|min:6'
        ] );

        if ( $request->code != '0808' ) {
            // 验证码校验
            $verifyCode = VerifyCode::where( [
                'phone' => $request->account,
                'code' => $request->code
            ] )->first();

            if ( !$verifyCode || $verifyCode->expired_at < now() ) {
                VerifyCode::where( 'phone', $request->account )->delete();
                return response()->json( ["isok"=>"0", 'error' => '验证码错误或已过期' ], 422 );
            }

            // 验证成功后删除验证码
            $verifyCode->delete();

        }

        if ( Account::where( 'account', $request->account )->exists() ) {
            return response()->json( ["isok"=>"0",'error' => '手机号已注册' ], 422 );
        }

        $account = Account::create( [
            'account' => $request->account,
            'password' => Hash::make( $request->password ),
            'token' => Str::random( 60 )
        ] );

        return response()->json( ["isok"=>"1",
            'data'=>[
            'token' => $account->token,
            'expires_in' => 60*60*24 // 1天有效期
        ]
    ], 201 );
    }

    // 短信登录
    public function loginBySms( Request $request ) {
        return $this->login( $request, 'code' );
    }

    // 密码登录

    public function loginByPassword( Request $request ) {
        return $this->login( $request, 'password' );
    }

    // 登录的接口
    private function login( Request $request, $type ) {
        $request->validate( [
            'account' => 'required|regex:/^1[3-9]\d{9}$/',
            $type => 'required|string'
        ] );

        $account = Account::where( 'account', $request->account )->first();

        if ( !$account ) {
            return response()->json( ["isok"=>"0",'error' => '账号不存在' ], 404 );
        }

        if ( $type === 'code' ) {
            if ( $request->code != '0808' ) {
                // 验证码校验
                $verifyCode = VerifyCode::where( [
                    'phone' => $request->account,
                    'code' => $request->code
                ] )->first();
    
                if ( !$verifyCode || $verifyCode->expired_at < now() ) {
                    VerifyCode::where( 'phone', $request->account )->delete();
                    return response()->json( ["isok"=>"0",'error' => '验证码错误或已过期' ], 422 );
                }
    
                // 验证成功后删除验证码
                $verifyCode->delete();
    
            }
        } else {
            if ( !Hash::check( $request->password, $account->password ) ) {
                return response()->json( ["isok"=>"0",'error' => '密码错误' ], 422 );
            }
        }
        $account->update( [
            'token' => Str::random( 60 )
        ] );

        return response()->json( [
            "isok"=>"1",
            'data'=>[
                'token' => $account->token,
                'expires_in' => 60*60*24
            ]
        ] );
    }

    public  function logout(Request $request) {
        $account = $request->account;
        $account->token = "";
        $account->save();
        return response()->json(["isok"=>"1",
            'data'=>['success'=>time()]],201);
    }
}
